package ua.dou.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.widget.Toast;
import ua.dou.loader.BaseLoaderCallback;
import ua.dou.loader.OnLoadFinishListener;
import ua.dou.loader.Response;

/**
 * Fragment with handling loader results.
 * User: David Mayboroda
 */
public abstract class LoaderFragment<MD> extends Fragment implements OnLoadFinishListener<MD>{

    /** Basic callback for fragment loaders.*/
    public Callback callback;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        callback = new Callback(this);
    }

    @Override
    public void onLoaderException(int id, Exception e) {
        if (e != null && !TextUtils.isEmpty(e.getMessage())) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    protected void setupLoader(final int id, final Bundle bundle) {
        getLoaderManager().initLoader(id, bundle, callback).forceLoad();
    }

    /** Callback implementation. */
    private class Callback extends BaseLoaderCallback<MD> {

        private Callback(OnLoadFinishListener<MD> listener) {
            super(listener);
        }

        @Override
        public Loader<Response<MD>> onCreateLoader(int id, Bundle args) {
            return createLoader(id, args);
        }
    }

    public abstract Loader<Response<MD>> createLoader(final int id, final Bundle bundle);

    @Override
    public void onDestroy() {
        callback = null;
        super.onDestroy();
    }
}
